<template>
    <div>
        <!-- 面包屑导航区 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图区 -->
        <el-card>
            <!-- 搜索区 -->
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>
            <!-- 表格展示区 -->
            <el-table :data="userList" border stripe>
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column prop="username" label="姓名"></el-table-column>
                <el-table-column prop="email" label="邮箱"></el-table-column>
                <el-table-column prop="mobile" label="电话"></el-table-column>
                <el-table-column prop="role_name" label="角色"></el-table-column>
                <el-table-column prop="mg_state" label="状态">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.mg_state" @change="handleUserStateChange(scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="240px">
                    <template slot-scope="scope">
                        <!-- 编辑按钮 -->
                        <el-button type="primary" icon="el-icon-edit" size="mini"
                            @click="showEditDialog(scope.row.id)"></el-button>
                        <!-- 删除按钮 -->
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)">
                        </el-button>
                        <!-- 分配用户角色按钮 -->
                        <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                            <el-button type="warning" icon="el-icon-setting" size="mini"
                                @click="showConfigDialog(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum" :page-sizes="[2, 5, 10, 20]" :page-size="100"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </el-card>
        <!-- 添加用户对话框 -->
        <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="40%" @close="handleAddDialogClose">
            <el-form :model="addForm" :rules="userFormRules" ref="addFormRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password" type="password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="mobile">
                    <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitAddForm">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 编辑用户对话框 -->
        <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="40%" @close="handleEditDialogClose">
            <el-form :model="editForm" :rules="userFormRules" ref="editFormRef" label-width="70px">
                <el-form-item label="用户名">
                    <el-input v-model="editForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="mobile">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitEditForm">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 分配角色对话框 -->
        <el-dialog title="分配角色" :visible.sync="configRoleDialogVisible" width="40%" @close="handleConfigDialogClose">
            <div>
                <p>当前的用户: {{ userInfo.username }}</p>
                <p>当前的角色: {{ userInfo.role_name }}</p>
                <p>分配新角色:
                    <el-select v-model="selectedRoleId" placeholder="请选择">
                        <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
                        </el-option>
                    </el-select>
                </p>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="configRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="setRoleInfo">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        var checkEmail = (rule, value, callback) => {
            const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/
            if (!emailPattern.test(value)) {
                callback(new Error('请输入合法的邮箱'));
            }
            callback()
        };
        var checkMobile = (rule, value, callback) => {
            const mobilePattern = /^1[3-9]\d{9}$/
            if (!mobilePattern.test(value)) {
                callback(new Error('请输入合法的手机号'));
            }
            callback()
        };
        return {
            queryInfo: {
                query: '',
                pagenum: 1,
                pagesize: 2,
            },
            // 需要被分配角色的用户对象
            userInfo: {},
            // 角色信息
            rolesList: [],
            selectedRoleId: '',
            userList: [],
            total: 0,
            addDialogVisible: false,
            editDialogVisible: false,
            configRoleDialogVisible: false,
            // 添加的用户表单对象
            addForm: {
                username: '',
                password: '',
                email: '',
                mobile: ''
            },
            // 添加用户的表单验证规则
            userFormRules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' },
                ],
                mobile: [
                    { required: true, message: '请输入手机号码', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' },
                ],
            },
            // 编辑用户表单对象
            editForm: {},
        }
    },
    created() {
        this.getUserList()
    },
    methods: {
        getUserList() {
            this.$http({
                url: 'users',
                params: this.queryInfo
            }).then(res => {
                this.userList = res.data.users
                this.total = res.data.total
            })
        },
        handleSizeChange(newSize) {
            this.queryInfo.pagesize = newSize
            this.getUserList()
        },
        handleCurrentChange(pageNum) {
            this.queryInfo.pagenum = pageNum
            this.getUserList()
        },
        handleUserStateChange(userInfo) {
            this.$http({
                url: `users/${userInfo.id}/state/${userInfo.mg_state}`,
                method: 'put'
            }).then((res) => {
                this.$message.success('更新状态成功')
            })
        },
        // 添加用户表单提交
        submitAddForm() {
            this.$refs.addFormRef.validate((valid) => {
                if (valid) {
                    // console.log('校验成功');
                    this.$http({
                        url: 'users',
                        method: 'post',
                        data: this.addForm
                    }).then((res) => {
                        if (res.meta.status === 201) {
                            this.$message.success('添加用户成功');
                            this.addDialogVisible = false
                            this.getUserList()
                        } else {
                            this.$message.error('添加用户失败:' + res.meta.msg);
                        }
                    })
                } else {
                    this.$message.error('校验失败');
                }
            });
        },
        // 关闭添加用户对话框事件
        handleAddDialogClose() {
            this.$refs.addFormRef.resetFields();
        },
        showEditDialog(id) {
            // 获取用户信息
            this.$http.get(`users/${id}`).then(({ data: res }) => {
                // console.log(res);
                this.editForm = res.data
                this.editDialogVisible = true
            })
        },
        showConfigDialog(userInfo) {
            this.userInfo = userInfo
            this.configRoleDialogVisible = true
            this.$http.get('roles').then((res) => {
                this.rolesList = res.data
            })
        },
        handleConfigDialogClose() {
            this.userInfo = {}
            this.selectedRoleId = ''
        },
        // 编辑用户表单提交
        submitEditForm() {
            this.$refs.editFormRef.validate((valid) => {
                if (valid) {
                    this.$http.put(`users/${this.editForm.id}`, this.editForm).then(() => {
                        this.editDialogVisible = false
                        this.getUserList()
                        this.$message.success('修改用户信息成功');
                    })
                }
            });
        },
        // 编辑用户表单重置
        handleEditDialogClose() {
            this.$refs.editFormRef.resetFields();
        },
        // 删除用户
        deleteUser(id) {
            this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$http.delete(`users/${id}`).then((res) => {
                    this.getUserList()
                })
            }).catch(() => {
                this.$message.info('已取消删除')
            });
        },
        // 提交为用户设置的权限
        setRoleInfo() {
            if (!this.selectedRoleId) {
                this.$message.error('请选择用户角色')
            } else if (this.selectedRoleId === this.userInfo.id) {
                this.$message.info('用户角色与选择相同')
            } else {
                this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectedRoleId }).then((res) => {
                    this.$message.success(res.meta.msg)
                    this.getUserList()
                    this.configRoleDialogVisible = false
                })
            }
        }
    }
}
</script>

<style scoped lang="less">
.el-table {
    /deep/ th {
        padding: 10px;
    }
    /deep/ td {
        padding: 5px;
    }
}
</style>